package com.xxx.rpc.starter;

import java.util.ArrayList;
import java.util.List;

import org.springframework.beans.factory.FactoryBean;
import org.springframework.util.StringUtils;

import com.xxx.rpc.common.annos.Reference;
import com.xxx.rpc.registry.zookeeper.ZooKeeperServiceDiscovery;


/**
 * @Referance注解使用的自定义的代理工厂，用于将指定的接口转换为代理实体
 */
public class StarterReferenceBeanFactory implements FactoryBean<Object>{
	private static List<Filter> filters=new ArrayList<Filter>();
	private Class<?> interfaceClass;
    private String  version;
    private static ZooKeeperServiceDiscovery zooKeeperServiceDiscovery;
    private boolean register=true;
	public Class<?> getInterfaceClass() {
		return interfaceClass;
	}

	public void setInterfaceClass(Class<?> interfaceClass) {
		this.interfaceClass = interfaceClass;
	}

	public String getVersion() {
		return version;
	}

	public void setVersion(String version) {
		this.version = version;
	}

	public StarterReferenceBeanFactory(Class<?> interfaceClass, String version,boolean register) {
		super();
		this.interfaceClass = interfaceClass;
		this.version = version;
		this.register=register;
	}
	
	public Object createBean() {
		RpcProxy rpcProxy = new RpcProxy(zooKeeperServiceDiscovery,filters,this.register);
		if(StringUtils.isEmpty(version)) {
			return  rpcProxy.create(interfaceClass);
		}
		return  rpcProxy.create(interfaceClass,version);
	}

	@Override
	public Object getObject() throws Exception {
		return createBean();
	}

	@Override
	public Class<?> getObjectType() {
		return interfaceClass;
	}

	public StarterReferenceBeanFactory() {
		super();
	}

	@Override
	public boolean isSingleton() {
		return false;
	}
	public static StarterReferenceBeanFactory getConsumerBean(String beanName, Class<?> field, Reference reference,RpcPorperties rpcPorperties) {
		zooKeeperServiceDiscovery=new ZooKeeperServiceDiscovery(rpcPorperties.getRegistry_address());
		return new StarterReferenceBeanFactory(field, reference.version(),rpcPorperties.isRegister());
	}
}